<template>
  <h4 style="text-align: center;">编辑用户</h4>
  <el-form
      ref="ruleFormRef"
      style="max-width: 600px; margin: auto;"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
  >
    <el-form-item label="昵称" prop="nick">
      <el-input v-model="ruleForm.nick"/>
    </el-form-item>

    <el-form-item label="性别" prop="sex">
      <el-select v-model="ruleForm.sex" placeholder="性别">
        <el-option label="男" value="男"/>
        <el-option label="女" value="女"/>
      </el-select>
    </el-form-item>

    <el-form-item label="手机" prop="phone">
      <el-input v-model="ruleForm.phone"/>
    </el-form-item>

    <el-form-item label="邮箱" prop="email">
      <el-input v-model="ruleForm.email"/>
    </el-form-item>
    <el-form-item label="住址" prop="address">
      <el-input v-model="ruleForm.address" type="textarea"/>
    </el-form-item>

    <el-form-item label="上传头像">
      <el-upload
          ref="avatarUploadRef"
          class="avatar-uploader"
          :action="'http://localhost:8180/api/user/avatar?uid=' + ruleForm.id"
          :auto-upload="false"
          :show-file-list="false"
          :limit="1"
          :on-exceed="handleAvatarExceed"
          :on-change="handleAvatarChange"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          accept="image/jpg,image/png,image/jpeg"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
        <el-icon v-else class="avatar-uploader-icon">
          <Plus/>
        </el-icon>
      </el-upload>
    </el-form-item>

    <el-form-item label="上传合同">
      <el-upload
          ref="contractUploadRef"
          class="upload-demo"
          :action="'http://localhost:8180/api/user/contract?uid=' + ruleForm.id"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceed"
          :on-success="handleContractSuccess"
          :on-error="handleContractError"
          accept="application/pdf"
      >
        <el-button type="primary">点击上传</el-button>
        <template #tip>
          <div class="el-upload__tip">
            pdf file with a size less than 5MB.
          </div>
        </template>
      </el-upload>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        确定
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup name="UserEdit">
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, genFileId} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {useRoute} from 'vue-router'
import {detail, modify, avatar} from '@/api/user'

const route = useRoute()

const ruleFormRef = ref()
const avatarUploadRef = ref()
const contractUploadRef = ref()

// do not use same name with ref
const ruleForm = reactive({
  id: '',
  nick: '',
  sex: '',
  phone: '',
  email: '',
  address: '',
})

const rules = reactive({
  nick: [
    {required: true, message: '请输入昵称', trigger: 'blur'},
    {min: 3, max: 16, message: '昵称长度范围3~16个字符', trigger: 'blur'},
  ],
  sex: [
    {required: true, message: '请输入性别', trigger: 'blur'},
  ],
  phone: [
    {required: true, message: '请输入手机', trigger: 'blur'},
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
  ],
  address: [
    {required: true, message: '请输入住址', trigger: 'blur'},
  ],
})

const imageUrl = ref('')

const doDetail = async () => {
  const id = route.params.id
  const result = await detail(id)
  if (result.code === 200) {
    Object.assign(ruleForm, result.data)
    await doAvatar(ruleForm.id)
  }
}

const doModify = async () => {
  const {id, nick, sex, phone, email, address} = ruleForm
  const result = await modify({id, nick, sex, phone, email, address})
  if (result.code === 200) {
    ElMessage.success("用户更新成功")
  }
}

const doAvatar =  async (uid) => {
  const result = await avatar(uid)
  if (result.code === 200) {
    imageUrl.value = result.data
  }
}

onMounted(() => {
  doDetail()
})

const handleAvatarExceed = (files) => {
  avatarUploadRef.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  avatarUploadRef.value.handleStart(file)
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const handleAvatarChange = (uploadFile, _) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
}

const handlerClearFile = () => {
  avatarUploadRef.value.clearFiles()
  contractUploadRef.value.clearFiles()
}

const handleAvatarSuccess = () => {
  ElMessage.success("头像上传成功")
}

const handleAvatarError = () => {
  ElMessage.error("头像上传失败")
}

const handleExceed/*: UploadProps['onExceed']*/ = (files) => {
  contractUploadRef.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  contractUploadRef.value.handleStart(file)
}

const handleContractSuccess = () => {
  ElMessage.success("合同上传成功")
}

const handleContractError = () => {
  ElMessage.error("合同上传失败")
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      doModify()
      // 文件上传
      avatarUploadRef.value.submit()
      contractUploadRef.value.submit()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
